<template>
	<view class="">
		<view class="mapBox" id="mapId"></view>
	</view>
</template>

<script module="leaflet" lang="renderjs">
	import jxJson from '@/static/jxJson.json';
	// import jxJson from '@/static/json/jxJson.json';
	export default {
		data() {
			return {
				map: null, //地图容器
				centerpoint: [37.6211, 114.9304676], //默认中心位置
				zoomlevel: 14, //初始化放大倍数
				baseLayer: null, //矢量底图
				markers: null,
				myGroup: {},
				ownerInstance: null, //接收视图层dom
			}
		},
		mounted() {
			// 动态引入较大类库避免影响页面展示
			const link = document.createElement('link');
			link.rel = "stylesheet"
			link.href = "https://unpkg.com/leaflet@1.9.3/dist/leaflet.css";
			document.head.appendChild(link)
			const script = document.createElement('script')

			script.src = "https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"
			script.type = "text/javascript"
			document.head.appendChild(script)
			script.onload = this.initMap.bind(this)
		},
		methods: {
			//初始化地图
			initMap() {
				console.log(11111111111111111);
				//底图
				const image = L.tileLayer(
					'http://t{s}.tianditu.gov.cn/img_w/wmts?tk=cb59b14d0b2d8f29c32ea8118cd5cebb&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}', {
						subdomains: [0, 1, 2, 3, 4, 5, 6, 7],
					})
				//注记
				const cia = L.tileLayer(
					'http://t{s}.tianditu.gov.cn/cia_w/wmts?tk=cb59b14d0b2d8f29c32ea8118cd5cebb&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}', {
						subdomains: [0, 1, 2, 3, 4, 5, 6, 7],
						transparent: true,
						zIndex: 3,
					})
				//天地图图组
				const tiandiMap = L.layerGroup([image, cia]);

				//地图对象
				this.map = L.map('mapId', {
					crs: L.CRS.EPSG3857,
					center: [27.682976, 115.857972],
					maxZoom: 18,
					zoom: 7,
					minZoom: 2,
					attributionControl: false,
					layers: [tiandiMap],
					zoomControl: false
				});
				image.addTo(this.map)
				cia.addTo(this.map)

				//江西省边界线
				L.geoJSON(jxJson, {
					"color": "blue",
					"weight": 3,
					"opacity": 0.4,
					"fillColor": "transparent",
					"fillOpacity": 0
				}).addTo(this.map)

				//遮罩层函数
				this.featureFn()
			},
			//遮罩层函数
			featureFn() {
				//遮罩层遮蔽层,geojson分两种情况
				var latlngs;
				var feature = jxJson["features"][0].geometry.coordinates
				if (feature[0][0][0] instanceof Array) {
					latlngs = feature[0]
				} else {
					latlngs = feature
				}

				var pNW = {
					lat: 59.0,
					lng: 73.0
				};
				var pNE = {
					lat: 59.0,
					lng: 136.0
				};
				var pSE = {
					lat: 3.0,
					lng: 136.0
				};
				var pSW = {
					lat: 3.0,
					lng: 73.0
				};
				//向数组中添加一次闭合多边形，并将西北角再加一次作为之后画闭合区域的起点
				var pArray = [];
				pArray.push(pNW);
				pArray.push(pSW);
				pArray.push(pSE);
				pArray.push(pNE);
				pArray.push(pNW);
				//循环添加各闭合区域
				for (var i = 0; i < latlngs.length; i++) {
					var points = [];
					for (let j = 0; j < latlngs[i].length; j++) {
						points.push({
							lat: Number(latlngs[i][j][1]),
							lng: Number(latlngs[i][j][0])
						});
					}
					//将闭合区域加到遮蔽层上，每次添加完后要再加一次西北角作为下次添加的起点和最后一次的终点
					pArray = pArray.concat(points);
					pArray.push(pArray[0]);
				}
				//反向遮蔽层
				let ahLayer = L.polygon(pArray, {
					color: 'transparent',
					fillColor: '#ebf0f6',
					fillOpacity: 0.6,
					renderer: L.canvas({
						padding: 1
					}) //解决遮罩层拖拽与缩放显示不全的Bug
				}); //建立多边形覆盖物
				ahLayer.addTo(this.map);
			},
			//属性psArr变化监控
			updatePsArr(newValue, oldValue, ownerInstance, instance) {
				console.log(newValue, 'newValue');
				if (newValue) {
					let _that = this
					if (Object.keys(this.myGroup).length) {
						this.myGroup.clearLayers()
					}
					setTimeout(function() {
						let marker
						let arrMark = []
						newValue.forEach(item => {

							let iconObj = L.icon({
								iconUrl: `https://www.jxdkchy.com:27705/markerImg/rw_point${item.missionStatus}.png`,
								iconSize: [17, 22]
							})
							marker = L.marker([_that.checkLat(item.lat), _that.checkLon(item.lon)], {
								icon: iconObj,
								data: item
							})
							marker.on('click', e => {
								// 点击marker点位，这里可以使用 uni.navigateTo
								uni.navigateTo({
									url: `/pages/form/form?options=${JSON.stringify(options)}`
								})
							})
							arrMark.push(marker)
						})
						let myGroup = L.layerGroup(arrMark);
						_that.map.addLayer(myGroup);
						_that.myGroup = myGroup
					}, 0);

				}
			},
			//  这个函数以及下面的那个函数是为了转化经纬度
			// 因为有时候返回的经纬度是 60进制，需要把他转化成 10 进制
			checkLon(lon) {
				let result = lon
				let index = lon.indexOf('.')
				if (index > 4) {
					let h = lon.substring(0, 3) * 1
					let m = lon.substring(3, 5) / 60
					let s = lon.substring(5) / 3600
					let digital = h + m + s
					result = digital.toFixed(8)
				} else if (index === -1) {
					if (lon.indexOf('°') !== -1) {
						let h = lon.substring(0, 3) * 1
						let m = lon.substring(4, 6) / 60
						let s = lon.substring(7, 9) / 3600
						let digital = h + m + s
						result = digital.toFixed(8)
					}
				}
				return result
			},
			checkLat(lat) {
				let result = lat
				let index = lat.indexOf('.')
				if (index > 4) {
					let h = lat.substring(0, 2) * 1
					let m = lat.substring(2, 4) / 60
					let s = lat.substring(4) / 3600
					let digital = h + m + s
					result = digital.toFixed(8)
				} else if (index === -1) {
					if (lat.indexOf('°') !== -1) {
						let h = lat.substring(0, 2) * 1
						let m = lat.substring(3, 5) / 60
						let s = lat.substring(6, 8) / 3600
						let digital = h + m + s
						result = digital.toFixed(8)
					}
				}
				return result
			},
			// 回到初始位置
			backInitCenterFn() {
				this.map.panTo([27.682976, 115.857972])
			}
		}
	}
</script>